var headerUploader = window.headerUploader = {
	init: function (launcherid,option) {
		var self = this,
			submitbtn,
			oldheader;
		if(option) uploadhconfig.diy = option;

		self.launcher = document.getElementById(launcherid) || document.querySelector(launcherid);
		self.launcher.style.backgroundImage = "url("+getConfig('defaultHeader')+")"; 
		if (!self.launcher)
			return console.error(self.ertext + "Can't not get element with parameter be given,please check!");
		self.launcher.onclick = function (e) {
			if (self.launcher.isuploadheaderalive) {
				alert("实例已经运行..");
				return;
			}
			if(self.Header){
				oldheader = self.Header;
				delete self.Header;
				self.launcher.removeAttribute("style");
			}
			if(option)
				self.ins = self.getTemplateInstance(option);
			else 
				self.ins = self.getTemplateInstance();
			document.body.appendChild(self.ins);
			showPreview(['#big-preview-icon', '#small-preview-icon'], self);
			self.shader = shaderIns('#header-shade', self);
			urlImageIns('#header-web-url', self);
			localImageIns('#header-img-file', self)
			submitbtn = document.getElementById('upload-header-btn');
			submitbtn.onclick = function(e){
				submitbtn.onclick = undefined;
				if(self.Header){
					var reader = new FileReader();
					reader.onload = function(e){
						self.launcher.style.backgroundImage = "url(" + e.currentTarget.result + ")";
						// self.launcher.style.color = "url(" + e.currentTarget.result + ")";
					}
					reader.readAsBinaryString(self.Header);
					self.destroy(e);
				}
			}
			defaultImageIns('#reset-to-default-header',self,getConfig('defaultHeader'));
			self.launcher.isuploadheaderalive = true;

			document.getElementById('header-uploader-close-btn').onclick = function (e) {
				if(!self.Header && oldheader){
					var reader = new FileReader();
					self.Header = oldheader;
					reader.onload = function(e){
						self.launcher.style.backgroundImage = "url(" + e.currentTarget.result + ")";
					}
					reader.readAsBinaryString(oldheader);
				}
				self.destroy(e);
			}
		}
		return self;
	},
	getTemplateInstance: function (option) {
		var self = this,
			tmp = document.createElement('div'),
			ins,
			subcanvas;
		option = option ? option : {};
		
		tmp.innerHTML = self.template.replace(/DEFAULT_FACE_ICON/, getConfig('defaultHeader'));
		ins = tmp.firstElementChild;
		ins.style.width = window.innerWidth * uploadhconfig.insScaleX;
		ins.style.height = window.innerHeight * uploadhconfig.insScaleY;
		subcanvas = self.canvas = canvasIns(ins.querySelector('#header-img-editor'));
		subcanvas.setAttribute('width',
			window.innerWidth * uploadhconfig.canvasScaleX);
		subcanvas.setAttribute('height',
			window.innerHeight * uploadhconfig.canvasScaleY);
		window.addEventListener('resize', function (e) {
			ins.style.width = window.innerWidth * uploadhconfig.insScaleX;
			ins.style.height = window.innerHeight * uploadhconfig.insScaleY;
		}, false);
		window.addEventListener('keydown', function (e) {
			if (self.ins && e.keyCode == 27)
				self.destroy(e);
		}, false);
		delete tmp;
		return ins;
	},
	destroy: function (e) {
		// 实例销毁函数
		var self = this;

		document.body.removeChild(self.ins);
		delete self.ins;
		delete self.canvas;
		delete self.shader;
		this.onclick = undefined;
		self.launcher.isuploadheaderalive = false;
	},
	ertext: '[@_@] headerUploader Error: ',
	template: "<div class='header-img-container'><a href='javascript: void(0);' id='header-uploader-close-btn' title='关闭'></a><div class='header-img-frame'><div class='left-content'><section class='url-input-widget-container'><label for='header-web-url'>图片的URL:</label><input type=\"text\" value=\"\" name=\"header-web-url\" id=\"header-web-url\" placeholder=\"输入或者黏贴网络头像url地址.\" /></section><div class=\"header-img-editor-area\" id=\"header-img-editor-area\"><canvas id=\"header-img-editor\">你的浏览器不支持canvas,请使用Chrome36以及更高版本或者FireFox浏览器使用...</canvas><div id=\"header-shade\"></div></div></div><div class=\"right-content\"><div class=\"big-preview-display\" id='big-preview-icon'></div><div class=\"small-preview-display\" id='small-preview-icon'></div><hr><a href=\"javascript:void(0);\" id=\"reset-to-default-header\"><img src=\"DEFAULT_FACE_ICON\"></a></div><div class=\"bottom-func-bar\"><label for=\"header-img-file\">选择图片<input type=\"file\" hidden='hidden' hidden name=\"header-img-file\" id=\"header-img-file\"/></label><a href=\"javascript:void(0);\" id=\"upload-header-btn\" class=\"btn\">确定</a></div></div></div>"
}


function getOnevh(n) {
	// 获取当前屏幕1vh的像素大小
	n = n == undefined ? 1 : n;
	return window.innerHeight / 100 * n;
}

function getOnevw(n) {
	// 获取当前屏幕1vw的像素大小
	n = n == undefined ? 1 : n;
	return window.innerWidth / 100 * n;
}

/**
 * 序列化canvas
 * @param {HTMLElement} canvas canvas元素实例
 */
function canvasIns(canvas) {
	var ctx = canvas.getContext('2d');

	/**
	 * 在canvas中显示指定图片
	 * @param {Image} img 图片实例对象
	 * @param {Function} callback 回调函数，返回参数canvas,context实例
	 */
	canvas.showimg = function (img, callback) {
		var self = this;
		ctx.drawImage(img, 0, 0, parseFloat(getComputedStyle(self)['width']), parseFloat(getComputedStyle(self)['height']));
		self.parentElement.className = [self.parentElement.className, 'header-img-editor-area-alive'].join('\u0020');

		return callback(canvas);
	}

	canvas.getHeaderImage = function (x, y, width, height) {
		var imagedata = ctx.getImageData(x, y, width, height),
			subcan = document.createElement('canvas'),
			subctx = subcan.getContext('2d');
		subcan.width = imagedata.width;
		subcan.height = imagedata.height;
		subctx.putImageData(imagedata, 0, 0);
		return subcan.toDataURL();
	}

	/**
	 * 调节canvas大小函数
	 * @param {Number} width 目标宽度
	 * @param {Number} height 目标高度
	 */
	canvas.resize = function (width, height) {
		var image = new Image(),
			self = this;
		image.src = self.toDataURL();
		self.width = width;
		self.height = height;
		ctx.drawImage(image, 0, 0, width, height);
	}
	return canvas;
}


function shaderIns(shadeId, parent) {
	var shader = querySelector(shadeId);

	shader.addEventListener('mousemove', function (e) {
		var self = this, // self == shader self
			pos = self.getBoundingClientRect();
		/**
		 * 调成遮罩层大小函数
		 * @param {Event} e 鼠标左键点击事件
		 */
		function resize(e) {
			var oldX, oldY;
			oldX = e.clientX;
			oldY = e.clientY;
			self.onmousemove = function (e) {
				var deltaX = e.clientX - oldX,
					deltaY = e.clientY - oldY;
				oldX = e.clientX;
				oldY = e.clientY;
				self.style.width = parseFloat(getComputedStyle(self)['width']) + deltaX + 'px';
				self.style.height = parseFloat(getComputedStyle(self)['height']) + deltaY + 'px';
				header = parent.canvas.getHeaderImage(self.offsetLeft, self.offsetTop, self.offsetWidth, self.offsetHeight);
				parent.preview(header);
			}
		}
		/**
		 * 移动遮罩层函数
		 * @param {Event} e 鼠标左键点击事件
		 */
		function move(e) {
			var oldX = e.clientX,
				oldY = e.clientY;
			self.onmousemove = function (e) {
				var deltaX = e.clientX - oldX,
					deltaY = e.clientY - oldY,
					header;
				oldX = e.clientX;
				oldY = e.clientY;
				if (self.offsetLeft + deltaX >= 0 && self.offsetLeft + self.clientWidth + deltaX <= parent.canvas.clientWidth)
					self.style.left = parseFloat(getComputedStyle(self)['left']) + deltaX + 'px';
				if (self.offsetTop + deltaY >= 0 && self.offsetTop + self.clientHeight + deltaY <= parent.canvas.clientHeight)
					self.style.top = parseFloat(getComputedStyle(self)['top']) + deltaY + 'px';
				header = parent.canvas.getHeaderImage(self.offsetLeft, self.offsetTop, self.offsetWidth, self.offsetHeight);
				parent.preview(header);
			}
		}
		/**
		 * 元素绑定元素清理函数
		 * @param {Event} e 
		 */
		function destroy(e) {
			self.onmouseup =
				self.onmouseout =
				self.onmousemove =
				parent.canvas.onmousemove =
				parent.canvas.onmouseout = undefined;
		}

		if (e.clientX - pos.left < pos.width - getOnevw() && e.clientY - pos.top < pos.height - getOnevh()) {
			self.style.cursor = 'move';
			self.onmousedown = move;
			self.onmouseup = self.onmouseout = parent.canvas.onmouseout = destroy;
		} else {
			self.style.cursor = 'se-resize';
			self.onmousedown = resize;
			self.onmouseup = self.onmouseout = destroy;
		}
	}, false);
	return shader;
}


/**
 * 初始化网络头像url输入控件
 * @param {String} urlimageid 接受外部头像url的输入控件id
 * @param {HTMLElement} parent uploadHeader实例
 * @return {HTMLElement} urlImage 返回输入控件实例
 */
function urlImageIns(urlimageid, parent) {
	var urlImage = querySelector(urlimageid);

	urlImage.addEventListener('focus', function (e) {
		if (e.target.value.trim())
			e.target.select();
	}, false);
	urlImage.onchange = function (e) {
		var imgurl = e.target.value.trim(),
			self = this,
			img = new Image(),
			canvas = parent.canvas;
		if (!imgurl) return;
		if (imgurl && imgurl.length < 50) return;
		if (!(imgurl.toLowerCase().startsWith('http://')) &&
			!(imgurl.toLowerCase().startsWith("https://"))) {
			alert("所给图片url地址不正确!");
			return undefined;
		}
		ajax(getConfig('imageUploadPath'), 'POST', {
			'imageurl': imgurl
		}, false, null, function (e) {
			img.src = JSON.parse(e.currentTarget.responseText)['imagepath']
			img.onload = function (e) {
				canvas.showimg(img, function (canvas) {
					parent.shader.setAttribute('class', 'header-shade-alive');
					var header = canvas.getHeaderImage(parent.shader.offsetLeft, parent.shader.offsetTop, parent.shader.offsetWidth, parent.shader.offsetHeight);
					parent.preview(header);
				});
			}
		}, function (e) {
			alert("所给地址不正确，或者是不支持的url类型")
		});

		img.onerror = function (e) {
			alert("无法加载所定义的头像图片，\n请尝试新的图片或者使用本地图片.")
		};
	};
	return urlImage;
}


/**
 * 本地图片上传处理函数
 * @param {String} localimageid 本地图片输入控件id
 * @param {HTMLElement} parent uploadHeader实例
 * @return {HTMLElement} localimage 本地输入控件实例
 */
function localImageIns(localimageid, parent) {
	var localimage = querySelector(localimageid);

	localimage.addEventListener('change', function (e) {
		var imgfile = e.target.files[0],
			reader = new FileReader(),
			img = new Image();
		if(!imgfile) return;
		reader.onload = function (e) {
			img.src = e.currentTarget.result;
			img.onload = function (e) {
				parent.shader.setAttribute('class', 'header-shade-alive');
				parent.canvas.showimg(img, function (canvas) {
					var header = parent.canvas.getHeaderImage(parent.shader.offsetLeft, parent.shader.offsetTop, parent.shader.offsetWidth, parent.shader.offsetHeight);
					parent.preview(header);
				});
			};
			img.onerror = function (e) {
				alert("图片类型不正确!");
			};
		};
		reader.readAsDataURL(imgfile);

	}, false);

	return localimage;
}



/**
 * 初始化预览控件
 * @param {Array} previewidlist 预览控件id列表
 * @param {HTMLElement} parent uploadHeader实例
 */
function showPreview(previewidlist, parent) {
	if (previewidlist && previewidlist instanceof Array) {
		var previewlist = new Object();
		for (var i = 0; i < previewidlist.length; i++)
			previewlist[i] = querySelector(previewidlist[i]);

		parent.preview = function (img) {
			if (!img) return;
			for (var key in previewlist)
				previewlist[key].style.backgroundImage = "url(" + img + ")";
			parent.Header = new Blob([img], {
				type: "image/jpeg"
			});
		}
	} else
		console.error("Parameter Error: Bad param be given.");
}


/**
 * @param {String} defaultHeaderid 默认头像按钮id
 * @param {HTMLElement} parent uploadHeader实例
 * @param {String} defaultHeader 默认头像的url地址
 */
function defaultImageIns(defaultHeaderid,parent,defaultHeader){
	var defaultFace = querySelector(defaultHeaderid);

	defaultFace.onclick = function(e){
		defaultFace.onclick = undefined;
		parent.Header = new Blob([defaultHeader],{type: "text/plain"});
		parent.launcher.style.backgroundImage = "url("+defaultHeader+")";
		parent.destroy(e);
	}
}


/**
 * Ajax 封装
 * @param {String} url 请求URL
 * @param {String} method 指定Http请求方法
 * @param {String} param 请求参数
 * @param {Boolean} sync 是否异步
 * @param {Object} option 可选参数
 * @param {Function} success 成功的回调函数
 * @param {Function} error 失败的回调函数
 */
function ajax(url, method, param, sync, option, success, error) {
	if (!sync) sync = false;
	var xhl, newparam = [];
	if (window.XMLHttpRequest) {
		xhl = new XMLHttpRequest();
		xhl.onreadystatechange = function (e) {
			if (xhl.readyState == 4 && xhl.status == 200) {
				// TO DO
				if (success && typeof success == 'function')
					success(e);
			} else if (xhl.readyState == 3 || xhl.readyState == 4) {
				if (error && typeof error == 'function')
					error(e);
			}
		}
	} else {
		alert("[QAQ] 你的破壁浏览器不支持Ajax，赶紧卸载了吧!!")
	}

	if (param) {
		if (method.toLowerCase() == 'get') {
			for (var key in param)
				newparam.push(key + '=' + param[key]);
			param = newparam.join('&')
			url = url + '?' + param
		} else {
			var form = new FormData();
			for (var key in param)
				form.append(key, param[key]);
			param = form
		}
	}
	xhl.open(method, url, sync)
	if (option)
		for (var key in option)
			xhl.setRequestHeader(key, option[key]);
	if (method.toLowerCase() == 'get')
		xhl.send();
	else
		xhl.send(param);
}


function querySelector(eleid){
	switch(eleid.substr(0,1)){
		case ".":
			return document.getElementsByClassName(eleid.substr(1));
		case "#":
			return document.getElementById(eleid.substr(1));
		case "[":
			return document.querySelector(eleid);
		default:
			return document.getElementsByTagName(eleid) || document.getElementsByName(eleid);
	}
}


/**
 * 设置配置项，配置项从默认配置文件uploadheader.config.js或者初始化的option参数中获取
 * @param {String} config 
 * @return {} 配置项
 */
function getConfig(config){
	return !uploadhconfig.diy || !uploadhconfig.diy[config] ? uploadhconfig[config]:uploadhconfig.diy[config];
}
